{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "import win32clipboard\n",
    "\n",
    "def set_html_to_clipboard(html_text):\n",
    "    # 构造符合Windows剪贴板要求的HTML格式\n",
    "    html_template = \"\"\"Version:0.9\n",
    "StartHTML:00000000\n",
    "EndHTML:00000000\n",
    "StartFragment:00000000\n",
    "EndFragment:00000000\n",
    "{}\"\"\"\n",
    "\n",
    "    # 计算各部分偏移量\n",
    "    html = html_template.format(html_text)\n",
    "    html = html.encode(\"utf-8\")\n",
    "    \n",
    "    start_html = html.find(b\"<html\")\n",
    "    end_html = len(html)\n",
    "    start_fragment = html.find(b\"<!--StartFragment-->\") + 20\n",
    "    end_fragment = html.find(b\"<!--EndFragment-->\")\n",
    "\n",
    "    # 替换占位符\n",
    "    html = html.replace(b\"00000000\", f\"{start_html:08}\".encode())\n",
    "    html = html.replace(b\"00000000\", f\"{end_html:08}\".encode(), 1)\n",
    "    html = html.replace(b\"00000000\", f\"{start_fragment:08}\".encode())\n",
    "    html = html.replace(b\"00000000\", f\"{end_fragment:08}\".encode())\n",
    "\n",
    "    # 写入剪贴板\n",
    "    win32clipboard.OpenClipboard()\n",
    "    win32clipboard.EmptyClipboard()\n",
    "    win32clipboard.SetClipboardData(win32clipboard.RegisterClipboardFormat(\"HTML Format\"), html)\n",
    "    win32clipboard.CloseClipboard()\n",
    "\n",
    "# 使用示例\n",
    "html_content = \"\"\"\n",
    "<html>\n",
    "<body>\n",
    "<!--StartFragment-->\n",
    "<p style=\"color: red;\">这是红色文字</p>\n",
    "<!--EndFragment-->\n",
    "</body>\n",
    "</html>\n",
    "\"\"\"\n",
    "set_html_to_clipboard(html_content)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
